<?php
/* 
* @Title:  [CMS顺序安装控制器]
* @Author: {chenlei} [chenleib5@126.com]
* @Date:   2014-03-27 09:05:21
* @Last Modified by:   Administrator
* @Last Modified time: 2014-03-28 19:35:09
* @Copyright:  [hn7m.com]
*/
class IndexControl extends Control{

	/**
	 * [__init 自动运行检测是否已经安装]
	 * @return [type] [description]
	 */
	public function __init(){
		if(is_file(ROOT_PATH.'Data/lock.php')){
			header('Content-type:text/html;charset=utf-8');
			die('您已经安装过cms,如果要重新安装,请先删除Install目录中的Data目录下的lock.php文件!');
		}

		$setup=include ROOT_PATH.'Data/setup.php';
		$this->assign('setup',$setup);
	}

	//版权信息|1
    public function index(){
        session('step',1);
        $this->display();
    }

    //检测环境|2
    public function check(){
    	if(session('step')<1) go(U('index'));

    	session('step',2);
    	//ini_get是获取php.ini里的环境变量的值.
    	//允许上传的单个文件最大值
    	$uploadsize=ini_get('upload_max_filesize');

    	$gd=gd_info();//获得GD库所有信息
    	$gdversion=$gd['GD Version'];
    	$diskspace=get_size(disk_free_space('.'));
    	$system=array(
    		"phpversion" => PHP_VERSION,
            "phpos" => PHP_OS,
            "uploadsize" => $uploadsize,
            "gdversion" => $gdversion,
            "diskspace" => $diskspace
    		);
    	$this->assign('system',$system);
    	$this->display();
    }

    //配置数据库连接|3
    public function setconfig(){
    	if(session('step')<2) go(U('check'));

    	session('step',3);
    	$this->display();
    }

    //安装数据库|4
    public function installdb(){
    	if (session('step')<3) go(U('setconfig'));

    	$_SESSION['adminpost']=Q('post.admin');

    	session('step',4);
    	$this->writeconfig();

    	$this->display();
    }
    //写入数据库配置
    public function writeconfig(){
    	$str = "<?php \r\n";
        $str.= "if(!defined('HDPHP_PATH'))exit('No direct script access allowed');\nreturn ";
        $str.= var_export(Q('post.db'), true);
        $str.=";\r\n";
        $dbconfigfile="../Cms/Common/Config/database.php";
        file_put_contents($dbconfigfile, $str);
    }

    //写入数据库
    public function createtable(){
    	if(session('step')<3) go(U('setconfig'));
    	session('step',4);

    	$dbConfig=include dirname(ROOT_PATH).'/Cms/Common/Config/database.php';
    	//连接数据库
    	$link=mysql_connect($dbConfig['DB_HOST'],$dbConfig['DB_USER'],$dbConfig['DB_PASSWORD']);
    	//如果有错误,则提示返回上一步
    	if(!$link){
            echo '<a href="'.U('setconfig').'" target="_parent">返回上一步</a><br/><br/>';
            header('Content-type:text/html;charset=utf-8');
            die('数据库连接错误，请返回上一步重新配置');
        }

        //设置编码
        mysql_query('SET CHARACTER_SET_CLIENT=BINARY,CHARACTER_SET_CONNECTION=UTF8,CHARACTER_SET_RESULTS=UTF8');

        //创建库,注意DATABASE后面有空格,charset前面有空格
        mysql_query('CREATE DATABASE '.$dbConfig['DB_DATABASE']. ' charset utf8');
        //使用库
        mysql_select_db($dbConfig['DB_DATABASE']);

        //创建表
        $sql=file_get_contents(ROOT_PATH."Data/cms_edu.sql");

        $preg="/;[\r\n]+/is";
        //把数据库每条语句组合为数组
        $sqlArr=preg_split($preg, $sql);

        //循环创建表，插入数据
        foreach ($sqlArr as $v) {
            if(preg_match("/CREATE\s+TABLE\s+`(.*?)`/is", $v,$t)){
                $temp = str_replace("CREATE TABLE `" . $t[1], "CREATE TABLE `" . $dbConfig['DB_PREFIX'] . $t[1], $v);
                //执行创建表
                $bool = mysql_query($temp);
                if($bool){
                    echo '<p style="font-size:12px;color:green">创建'.$dbConfig['DB_PREFIX'] . $t[1].'成功</p>';
                }else{
                    echo '<p style="font-size:12px;color:red">创建'.$dbConfig['DB_PREFIX'] . $t[1].'失败</p>';
                }
            }
            if(preg_match("/INSERT\s+INTO\s+`(.*?)`/is", $v, $tt)){
                $temp = str_replace("INSERT INTO `" . $tt[1], "INSERT INTO `" . $dbConfig['DB_PREFIX'] . $tt[1], $v);
                $bool = mysql_query($temp);
                if(!$bool){
                    echo '<p style="font-size:12px;color:red">'.$dbConfig['DB_PREFIX'] . $tt[1].'插入数据失败</p>';
                    die;
                }
            }
        }

        //插入后台管理员信息
        $adminPost = session('adminpost');
        $username = $adminPost['username'];
        $password = md5($adminPost['password']);
        $mail = $adminPost['email'];

        $sql = "INSERT INTO `" . $dbConfig['DB_PREFIX'] . "user` (username,nickname,password,is_admin,supper,email) VALUES ('$username','超级管理员','$password',1,1,'$mail')";
        mysql_query($sql);

        //1秒之后跳转
        echo "<script type='text/javascript'>
        setTimeout(function(){
            parent.location.href='?m=finish';
        },1000);
        </script>";

    }

    //完成安装|5
    public function finish(){
         if ($_SESSION['step'] < 4) {
            go("index");
        }
        file_put_contents(ROOT_PATH . 'Data/lock.php', '安装时间:'.date('Y-m-d H:i:s').'<br/>如需重新安装程序,请先删除本文件!') || die('access not allowed');
        $url = array(
            'front_url' =>  dirname(__ROOT__),
            'admin_url' =>  dirname(__ROOT__) . '/admin.php'
            );
        $this->assign('url',$url);
        $this->display();
      }
}
?>